extends "res://base/base_lobby.gd"

signal on_destory_event(id : int)

func _ready() -> void:
	_create_room("Lobby")
	_create_room("Lobby2")
	_init_net_manage()

func _init_signal() -> void : pass

func _on_peer_connected_event(_id: int) :
	#载入大厅场景与人物
	_init_player(_id)

func _on_peer_disconnected_event(id: int) -> void :
	on_destory_event.emit(id)

func _on_auth_callback(_id: int, _data: Dictionary) -> bool :
	return _data.password == "123"

func _init_net_manage() -> void :
	NetManage._auth_callback = _on_auth_callback
	NetManage._on_connected_event.connect(_on_peer_connected_event)
	NetManage._on_disconnected_event.connect(_on_peer_disconnected_event)
	NetManage._create_multiplayer(multiplayer)
	multiplayer.multiplayer_peer = NetManage.peer

func _init_player(id: int) -> void :
	var player = Global.BASE_PLAYER.instantiate()
	player.name = str(id)
	on_destory_event.connect(player._on_destory_event)
	var lobby = room_list.get("Lobby")
	lobby.call_deferred("add_child",player)
	player_list.set(id,player)

func _create_room(room_name : String = "Lobby") -> Node2D :
	var room = Global.TEMP_ROOM.instantiate()
	room.name = room_name
	get_tree().current_scene.call_deferred("add_child",room)
	room_list.set(room_name,room)
	return room

@rpc("any_peer")
func _change_room(room_name : String) :
	var room = room_list.get(room_name)
	var id = multiplayer.get_remote_sender_id()
	var player = player_list.get(id)
	_player_change_room(player,room)
